import { Login, Logout, IsLogin } from "@/api/user.js";
import { Auth } from "@/api/auth.js";
const state = {
  user:{},
  isLogin: false,  
};

const getters = {
  user: (state) => state.user,
  isLogin: (state) => state.isLogin,
};

const actions = {
  async login(context, user) {
    let result = await Login(user);
    if (result.code == 1) {
      context.commit("setUser", result.data.user);
      context.commit("setIsLogin", true);
      Auth.setAuthorization(result.data.session_id); //      
    }
    return result;
  },
  async islogin(context) {
    let result = await IsLogin();
    if (result.code == 1) {
      context.commit("setUser", result.data.user);
      context.commit("setIsLogin", true);
      Auth.setAuthorization(result.data.session_id); //
      localStorage.setItem("user",result.data.user);
    }
    return result;
  },

  async logout(context) {
    let result = await Logout();
    if (result.code == 1) {
      context.commit("logout");
      Auth.setAuthorization("");
      localStorage.setItem("user",{});
    }
    return result;
  },
};

const mutations = {
  logout(state) {
    state.isLogin = false;
    state.user = {};    
  },

  setUser(state, user) { //user={id,name}    
    state.user = user;
  },

  setIsLogin(state, isLogin) {    
    state.isLogin = isLogin;
  }, 
};

export default {
  namespaced: true,
  state,
  getters,
  actions,
  mutations,
};
